package com.imau.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter("/*")
public class LoginFilter implements Filter {
    //1.定义拦截请求的白名单
    private static final String[] whiteList = {"/login.html", "/css/*", "/js/*", "/imgs/*", "/login",

            "/register.html", "/register", "/checkCode", "/userCheckNameServlet"};

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    /**
     * 判断是否在白名单中
     *
     * @param path
     * @return
     */
    public boolean isWhite(String path) {
        ///servlet-loginCase2/login.html
        for (String s : whiteList) {
            if (path.contains(s)) {
                return true;
            }
        }

        return false;
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //1.对象转换
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        //设置编码
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");

        //获取请求路径
        String requestURI = request.getRequestURI();
        //判断是否白名单的路径
        if (isWhite(requestURI)) {
            //在白名单放行
            filterChain.doFilter(servletRequest, servletResponse);
        } else {

            //不在白名单，判断session中是否有用户信息
            Object user = request.getSession().getAttribute("user");
            if (user != null) {
                filterChain.doFilter(servletRequest, servletResponse);
            } else {
                response.sendRedirect(request.getContextPath() + "/login.html");
                filterChain.doFilter(servletRequest, servletResponse);
            }
        }
    }

    @Override
    public void destroy() {
    }
}